package com.huawei.hmsdemo10086.Activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.huawei.agconnect.config.AGConnectServicesConfig;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.aaid.HmsInstanceId;
import com.huawei.hms.common.ApiException;

import com.huawei.hms.push.HmsMessageService;
import com.huawei.hms.support.account.AccountAuthManager;
import com.huawei.hms.support.account.request.AccountAuthParams;
import com.huawei.hms.support.account.request.AccountAuthParamsHelper;
import com.huawei.hms.support.account.result.AuthAccount;
import com.huawei.hms.support.account.service.AccountAuthService;
import com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton;
import com.huawei.hmsdemo10086.POJO.User;
import com.huawei.hmsdemo10086.R;
import com.huawei.hmsdemo10086.POJO.Result;
import com.huawei.hmsdemo10086.UserService;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class LoginActivity extends AppCompatActivity {

    private static final String TAG = "LoginActivity";
    private HuaweiIdAuthButton hw_sign_in;
    private TextView phone;
    private TextView password;
    private static final String APP_ID = "1112023886";//官方获取的APPID
    private Tencent mTencent;
    private BaseUiListener mIUiListener;
    private UserInfo mUserInfo;
    //private SharedPreferences sharedPreferences;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        getToken();

        //sharedPreferences = getSharedPreferences("userInfo",MODE_PRIVATE);
        //传入参数APPID和全局Context上下文
        mTencent = Tencent.createInstance(APP_ID, LoginActivity.this.getApplicationContext());
        initView();
    }

    public void buttonLogin(View v) {
        /**通过这句代码，SDK实现了QQ的登录，这个方法有三个参数，第一个参数是context上下文，第二个参数SCOPO 是一个String类型的字符串，表示一些权限
         官方文档中的说明：应用需要获得哪些API的权限，由“，”分隔。例如：SCOPE = “get_user_info,add_t”；所有权限用“all”
         第三个参数，是一个事件监听器，IUiListener接口的实例，这里用的是该接口的实现类 */
        mIUiListener = new BaseUiListener();
        //all表示获取所有权限
        mTencent.login(LoginActivity.this, "all", mIUiListener);
    }

    /**
     * 自定义监听器实现IUiListener接口后，需要实现的3个方法
     * onComplete完成 onError错误 onCancel取消
     */
    private class BaseUiListener implements IUiListener {
        @Override
        public void onComplete(Object response) {
            Toast.makeText(LoginActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "response:" + response);
            JSONObject obj = (JSONObject) response;
            try {
                String openID = obj.getString("openid");
                String accessToken = obj.getString("access_token");
                String expires = obj.getString("expires_in");
                mTencent.setOpenId(openID);
                mTencent.setAccessToken(accessToken, expires);
                QQToken qqToken = mTencent.getQQToken();
                mUserInfo = new UserInfo(getApplicationContext(), qqToken);
                mUserInfo.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object response) {
                        Log.e(TAG, "登录成功" + response.toString());
                    }

                    @Override
                    public void onError(UiError uiError) {
                        Log.e(TAG, "登录失败" + uiError.toString());
                    }

                    @Override
                    public void onCancel() {
                        Log.e(TAG, "登录取消");
                    }

                    @Override
                    public void onWarning(int i) {

                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(LoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(LoginActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onWarning(int i) {

        }
    }


    private void initView() {

        hw_sign_in = (HuaweiIdAuthButton) findViewById(R.id.huawei_login);
        Button log_button = (Button) findViewById(R.id.login_button);
        phone = (TextView) findViewById(R.id.phone);
        password = (TextView) findViewById(R.id.password);
        Button qq_button = (Button) findViewById(R.id.qq_login);
        Button register_button = (Button) findViewById(R.id.to_register);


        register_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegesitActivity.class);

                startActivity(intent);
            }
        });

        qq_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                buttonLogin(v);
            }
        });

        hw_sign_in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gengerSignIn();
            }
        });

        log_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!isMobileNO(phone.getText().toString())){
                    Toast.makeText(LoginActivity.this, "手机号格式不正确", Toast.LENGTH_LONG).show();
                }else if(password.length()<=0) {
                    Toast.makeText(LoginActivity.this, "密码不为空", Toast.LENGTH_LONG).show();
                }else{
                    sendPost();
                }

            }
        });

    }

    private void sendPost() {
        String url = "http://10.0.2.2:8443/api/login";
        OkHttpClient mOkHttpClient = new OkHttpClient();

        String json = "{\n" +
                "  \"phone\": \"" + phone.getText().toString() + "\",\n" +
                "  \"password\": \"" + password.getText().toString() + "\"\n" +
                "}";
        Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"), json)).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("测试", e + "");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                Gson gson = new Gson();
                String rep = response.body().string();
                System.out.println(rep);
                Type type = new TypeToken<Result<User>>() {
                }.getType();
                Result<User> result = gson.fromJson(rep, type);

                if (result.getCode() == 200) {
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    SharedPreferences sharedPreference = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreference.edit();
                    editor.putString("userName", result.getData().getUsername());
                    editor.putString("userId", "" + result.getData().getUserid());
                    editor.putBoolean("isVIP", result.getData().getisVIP());
                    editor.putFloat("point", (float) result.getData().getPoint());
                    editor.commit();
                    startActivity(intent);
                    finish();
                } else {
                    Looper.prepare();
                    Toast.makeText(LoginActivity.this, "用户名或者密码错误", Toast.LENGTH_SHORT).show();
                    Looper.loop();
                }

            }

        });


    }

    private void gengerSignIn() {
        AccountAuthParams authParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setIdToken().createParams();
        AccountAuthService service = AccountAuthManager.getService(LoginActivity.this, authParams);
        startActivityForResult(service.getSignInIntent(), 8888);

    }

    /**
     * 在调用Login的Activity或者Fragment中重写onActivityResult方法
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //授权登录结果处理，从AuthAccount中获取ID Token
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 8888) {
            Task<AuthAccount> authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data);
            if (authAccountTask.isSuccessful()) {
                //登录成功，获取用户的帐号信息和ID Token
                AuthAccount authAccount = authAccountTask.getResult();
                Log.i(TAG, "idToken:" + authAccount.getIdToken());
                //获取帐号类型，0表示华为帐号、1表示AppTouch帐号
                Log.i(TAG, "accountFlag:" + authAccount.getAccountFlag());
                Intent intent = new Intent(LoginActivity.this, BindActivity.class);
                intent.putExtra("token", authAccount.getIdToken());
                checkexit(authAccount.getIdToken());
            } else {
                //登录失败，不需要做处理，打点日志方便定位
                Log.e(TAG, "sign in failed : " + ((ApiException) authAccountTask.getException()).getStatusCode());
            }
        } else if (requestCode == Constants.REQUEST_LOGIN) {
            Tencent.onActivityResultData(requestCode, resultCode, data, mIUiListener);
        }
    }

    public void checkexit(String token) {
        String url = "http://10.0.2.2:8443/api/checkexitbytoken";
        OkHttpClient mOkHttpClient = new OkHttpClient();

        String json = "{\n" +
                "  \"token\": \"" + token + "\"\n" +
                "}";


        Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"), json)).build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("测试", e + "");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {


                Gson gson = new Gson();
                String rep = response.body().string();
                System.out.println(rep);
                Type type = new TypeToken<Result<User>>() {
                }.getType();
                Result<User> result = gson.fromJson(rep, type);

                if (result.getCode() == 200)//已经绑定
                {
                    SharedPreferences sharedPreference = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreference.edit();
                    editor.putString("userName", result.getData().getUsername());
                    editor.putString("userId", "" + result.getData().getUserid());
                    editor.putBoolean("isVIP", result.getData().getisVIP());
                    editor.putFloat("point", (float) result.getData().getPoint());
                    editor.commit();
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    Intent intent = new Intent(LoginActivity.this, BindActivity.class);
                    intent.putExtra("token", token);
                    startActivity(intent);
                    finish();
                    // Toast.makeText(LoginActivity.this, "用户名或者密码错误", Toast.LENGTH_SHORT).show();
                }

            }

        });
    }

    private void getToken() {
        // Create a thread.
        new Thread() {
            @Override
            public void run() {
                try {
                    // Obtain the app ID from the agconnect-service.json file.
                    String appId = AGConnectServicesConfig.fromContext(LoginActivity.this).getString("client/app_id");
                    // Set tokenScope to HCM.
                    String tokenScope = "HCM";
                    String token = HmsInstanceId.getInstance(LoginActivity.this).getToken(appId, tokenScope);
                    Log.i(TAG, "get token: " + token);

                    // Check whether the token is empty.
                    if (!TextUtils.isEmpty(token)) {
                        sendRegTokenToServer(token);
                    }
                } catch (ApiException e) {
                    Log.e(TAG, "get token failed, " + e);
                }
            }
        }.start();
    }

    private void sendRegTokenToServer(String token) {
        Log.i(TAG, "sending token to server. token:" + token);
    }


    public static boolean isMobileNO(String mobileNums) {
        String telRegex = "^((13[0-9])|(14[5,7,9])|(15[^4])|(18[0-9])|(17[0,1,3,5,6,7,8]))\\d{8}$";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        return mobileNums.matches(telRegex);
    }


}
